﻿using DevExpress.Persistent.BaseImpl;
using DevExpress.Persistent.Validation;
using DevExpress.Xpo;
using System.ComponentModel;

namespace EasyXaf.DataDictionaries;

[Persistent]
[System.ComponentModel.DisplayName("字典项")]
public class DataDictionaryItem : BaseObject
{
    private string _name;
    private string _code;
    private string _description;
    private int _order;
    private DataDictionary _dataDictionary;

    [RuleRequiredField]
    [System.ComponentModel.DisplayName("名称")]
    public string Name
    {
        get => _name;
        set => SetPropertyValue(nameof(Name), ref _name, value);
    }

    [System.ComponentModel.DisplayName("编码")]
    public string Code
    {
        get => _code;
        set => SetPropertyValue(nameof(Code), ref _code, value);
    }

    [System.ComponentModel.DisplayName("描述")]
    public string Description
    {
        get => _description;
        set => SetPropertyValue(nameof(Description), ref _description, value);
    }

    [System.ComponentModel.DisplayName("顺序")]
    public int Order
    {
        get => _order;
        set => SetPropertyValue(nameof(Order), ref _order, value);
    }

    [Association("DataDictionary-Items")]
    public DataDictionary DataDictionary
    {
        get => _dataDictionary;
        set => SetPropertyValue(nameof(DataDictionary), ref _dataDictionary, value);
    }

    [Browsable(false)]
    [RuleFromBoolProperty("字典项名称必须唯一", DefaultContexts.Save, CustomMessageTemplate = "字典项名称已存在")]
    public bool IsNameUnique
    {
        get => !DataDictionary.Items.Any(item => item.Name == Name && item != this);
    }

    public DataDictionaryItem(Session session)
        : base(session)
    {
    }

    protected override void OnSaving()
    {
        base.OnSaving();

        if (Order == 0 && DataDictionary.Items.Count > 1)
        {
            Order = DataDictionary.Items.Max(item => item.Order) + 1;
        }
    }
}
